// components/game_scan/game_scan.js
import LAN from '../../utils/lan';

const app = getApp();
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    avatarUrl:{
      type:String,
      value:''
    },
    nickName:{
      type:String,
      value:''
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    list:[],

  },

  /**
   * 组件的方法列表
   */
  methods: {

    onSubmit(e) {
      const { port } = e.detail.value;
      let num = Number.parseInt(port);
      //fail Port should be > 0 and < 65536. Received undefined
      if (num<1 || num>65535) {
        app.showModal('端口号在1~65535之间');
        return;
      }
  
      this.startScanOnlineDevice({
        port:num,
        success:res=>{
          let list = [];
          let address;
          res.list.forEach(function(device){
            const { localInfo, remoteInfo, message } = device;
            if(!address) address=localInfo.address;
            let index = list.findIndex(m=>m.address==remoteInfo.address);
            if(index>=0) return;
            const { nickName, avatarUrl, gameID, gameName, gameState } = message;
            list.unshift({
              gameID,
              gameName,
              gameState,
              nickName,
              avatarUrl,
              address:remoteInfo.address,
              port:remoteInfo.port
            });
          });
          this.setData({ list, address:address || '0.0.0.0' });
          app.showToast({
            icon:'success',
            title:'扫描完成！'
          });
          // console.log(res)
        },
        fail(err){
          app.showModal(err.errMsg);
        }
      });
      
    },
  
    startScanOnlineDevice(e){
      LAN.sendBroadcast({
        port: e.port || 55555,
        fail:e.fail,
        showLoading:'扫描中',
        success(res){
          e.success(res);
        }
      })
    },
  
    onClickItem(e){
      const { index } = e.currentTarget.dataset;
      let item = this.data.list[index];
      this.triggerEvent('itemtap',item)
    }
  }
})
